using System;
using UnityEngine;


namespace EventBehaviorTree
{
    [Serializable]
    public class Sequencer : Container<ContainerMode>
    {
        public Sequencer(string workMode = "Async")
        {
            _workMode = (ContainerMode)Enum.Parse(typeof(ContainerMode), workMode);
            Condition = () => _stepCount == _subNodes.Count;//all sub nodes done
            //if condition is "stepCounter == subNodes.Count - 1", the message may be sended before the last node working.
        }

        public override void NodeEvent(NodeMessage nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMessage.Start:
                    //Debug.Log(this + "/ " + Key);
                    _stepCount = 0;
                    ResetWorker();
                    _coroutineStarter.StartCoroutine(_worker);
                    _subNodes[0].NodeEvent(NodeMessage.Start);
                    return;
                case NodeMessage.Success:
                    if (_stepCount < _subNodes.Count - 1)
                    {
                        _subNodes[++_stepCount].NodeEvent(NodeMessage.Start);
                        return;
                    }
                    _stepCount++;//the last sub node will do this: all successed
                    return;
                case NodeMessage.Failure:
                    ResetWorker();
                    StopAllSubNodes();
                    SeniorNodeEvent(NodeMessage.Failure);
                    return;
                case NodeMessage.COMMAND_Stop:
                    ResetWorker();
                    StopAllSubNodes();
                    return;
                case NodeMessage.REQUEST_Abort://[CONSIDER]
                    ResetWorker();
                    StopAllSubNodes();
                    SeniorNodeEvent(NodeMessage.Success);//[HelpDoc]
                    return;
                default:
                    break;
            }
        }
    }
}
